package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"time"
	"weibo-kit/cache"
	"weibo-kit/models"
	"weibo-kit/pkg"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "字段不能为空",
		})
		return
	}
	Reds_key := "Reds_key_" + username
	Reds_count, _ := cache.Rdb.Get(cache.Ctx, Reds_key).Int()
	if Reds_count >= 3 {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "登录失败三次，禁止登录",
		})
		return
	}
	var user models.User
	err := models.DB.Where("username=?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "用户不存在",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "用户不存在",
		})
		return
	}
	if pkg.Md5(password) != password {
		cache.Rdb.Incr(cache.Ctx, Reds_key)
		if Reds_count == 2 {
			cache.Rdb.Set(cache.Ctx, Reds_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 400,
				"msg":  "登录已上锁，2小时后解锁",
			})
			return
		}
		c.JSON(200, gin.H{

			"code": 400,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"user": user,
	})
}
func Role(c *gin.Context) {
	rid := c.Query("rid")

	var role []models.Role
	/*
	   SELECT*FROM
	   roles
	   LEFT JOIN user_roles ON user_roles.rid=roles.id
	   WHERE user_roles.rid=1
	*/

	models.DB.Table("roles").
		Joins("LEFT JOIN user_roles ON user_roles.rid=roles.id").
		Where("user_roles.rid=?", rid).Debug().Find(&role)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"list": role,
	})

}
func Nodes(c *gin.Context) {
	rid := c.Query("rid")

	/*
		SELECT*FROM
		nodes
		LEFT JOIN role_nodes ON role_nodes.rid=nodes.id
		WHERE role_nodes.rid=2
	*/
	var arr []models.Node
	models.DB.Table("nodes").Joins("LEFT JOIN role_nodes ON role_nodes.rid=nodes.id").
		Where("role_nodes.rid=?", rid).Find(&arr)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"list": arr,
	})
}
func List(c *gin.Context) {
	var arr []models.WbList
	red_key := "redis_list"
	redsData, _ := cache.Rdb.Get(cache.Ctx, red_key).Result()
	if redsData == "" {
		models.DB.Find(&arr)
		jsondata, _ := json.Marshal(arr)
		cache.Rdb.Set(cache.Ctx, red_key, jsondata, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redsData), &arr)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"list": arr,
	})
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var arr []models.WbList
	red_key := "redis_detail" + id
	redsData, _ := cache.Rdb.Get(cache.Ctx, red_key).Result()
	if redsData == "" {
		models.DB.Where("id=?", id).Find(&arr)
		jsondata, _ := json.Marshal(arr)
		cache.Rdb.Set(cache.Ctx, red_key, jsondata, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redsData), &arr)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "详情成功",
		"list": arr,
	})
}
